package com.ruoyi.project.mobile.user;

import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.uniquekey.IdGererateFactory;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.project.AppBeanInjector;
import com.ruoyi.project.system.coinrecord.domain.HaoqiCoinRecord;
import com.ruoyi.project.system.coinrecord.service.IHaoqiCoinRecordService;
import com.ruoyi.project.system.member.domain.Member;
import com.ruoyi.project.system.member.enums.MemberIsVip;
import com.ruoyi.project.system.member.enums.MemberStatus;
import com.ruoyi.project.system.member.service.IMemberService;
import com.ruoyi.project.system.paylog.domain.PayLog;
import com.ruoyi.project.system.paylog.service.IPayLogService;
import com.ruoyi.project.system.shopconfig.domain.ShopConfig;
import com.ruoyi.project.system.shopconfig.service.IShopConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

/**
 * 功能：
 *
 * @author：dell
 * @create：2020/6/29 18:19
 * @version：2020 Version：1.0
 * @company：老屋新房 Created with IntelliJ IDEA
 */
@RestController
@RequestMapping("/api/vip")
public class ApiOpenVipController extends BaseController {

	@Autowired
	private IMemberService memberService;

	@Resource
	private IdGererateFactory idGererateFactory;

	@Autowired
	private IShopConfigService shopConfigService;

	@Autowired
	private IHaoqiCoinRecordService haoqiCoinRecordService;

	@Autowired
	private IPayLogService payLogService;

	/**
	 * 获取开通会员信息
	 * @param uid
	 * @return
	 */
	@GetMapping("/config")
	public R vipConfig(@RequestParam String uid){
		ShopConfig shopConfig = this.shopConfigService.findAll().get(0);
		HashMap<String, Object> map = new HashMap<>();
		Member oldMember = this.memberService.selectMemberById(uid);

		//当前用户是否是vip
		map.put("isVip",oldMember.getIsVip());

		map.put("vipPrice",oldMember.getIsInside()==0?shopConfig.getVipPrice():shopConfig.getInsidePrice());
		return RFactory.generateR(map);
	}


	/**
	 * 开通会员
	 * @param uid
	 * @param req
	 * @return
	 */
	@GetMapping("/wxpay")
	public R vipPay(@RequestParam String uid, HttpServletRequest req){
		//查询用户是否存在
		Member member = this.memberService.selectMemberById(uid);
		if(member==null){
			return R.error("用户不存在");
		} else if (member.getIsVip() == 1) {
		    return R.error("用户已经是会员");
        } else if(member.getIsExamine()!=2){
			return R.error("必须先实名认证");
		}
		//获取会员价格
		ShopConfig shopConfig = this.shopConfigService.findAll().get(0);


		HashMap<String, Object> map = new HashMap<>();
        Member oldMember = this.memberService.selectMemberById(uid);
        map.put("vipPrice",oldMember.getIsInside()==0?shopConfig.getVipPrice():shopConfig.getInsidePrice());

		//时间戳
		map.put("timeStamp",DateUtils.getNowDate().getTime()+"");

		//调用统一下单接口拿到prepay_id
		SortedMap<String, Object> date = new TreeMap<String,Object>();

		//返回用前端的date2
		SortedMap<String, Object> date2 = new TreeMap<String,Object>();
		date2.put("appId",AppBeanInjector.weixinConfig.getAppId());
		date2.put("timeStamp",DateUtils.getNowDate().getTime());
		date2.put("signType","MD5");

		date.put("appid",AppBeanInjector.weixinConfig.getAppId());
		date.put("attach","富利地产开通会员");
		date.put("openid",member.getOpenid());
		date.put("body","富利地产开通会员");
		date.put("mch_id",AppBeanInjector.weixinConfig.getMch_id());
		date.put("nonce_str",this.idGererateFactory.nextStringId());
		date.put("notify_url",AppBeanInjector.weixinConfig.getVip_notify_url());
		date.put("out_trade_no",member.getId()+"-"+this.idGererateFactory.nextStringId());
		date.put("spbill_create_ip",StringUtils.getRemoteAddr(req));
		float sessionmoney = Float.parseFloat((member.getIsInside()==0?shopConfig.getVipPrice():shopConfig.getInsidePrice()).toString());
		String finalmoney = String.format("%.2f", sessionmoney);
		finalmoney = finalmoney.replace(".", "");
		String newStr = finalmoney.replaceFirst("^0*", "");
		date.put("total_fee",newStr);
		date.put("trade_type","JSAPI");
		String perpayId = WeixinUtils.getPerpayId(date,date2);

		date2.put("package",FBSStringUtil.format("prepay_id={0}",perpayId));

		map.put("package",FBSStringUtil.format("prepay_id={0}",perpayId));
		//paySign 签名
		map.put("paySign",WeixinUtils.createSign(WeixinUtils.CHARSET,date2));
		//随机字符串
		map.put("nonceStr",date2.get("nonceStr"));

		//生成支付记录
		PayLog payLog = new PayLog();
		payLog.setOutTradeNo((String) date.get("out_trade_no"));
		payLog.setStatus(0);
		payLog.setType(0);
		payLog.setCreated(DateUtils.getNowDate());
		payLog.setMemberId(uid);
		payLog.setResId(uid);
		payLog.setPrice(member.getIsInside()==0?shopConfig.getVipPrice():shopConfig.getInsidePrice());
		this.payLogService.insertPayLog(payLog);

		return RFactory.generateR(map);
	}


	/**
	 * 微信回调方法
	 * @param req
	 * @param res
	 * @return
	 */
	@PostMapping("/result")
	@Transactional
	public Object vipResult(HttpServletRequest req, HttpServletResponse res){
		try {
			InputStream inStream = req.getInputStream();
			ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = inStream.read(buffer)) != -1) {
				outSteam.write(buffer, 0, len);
			}
			System.out.println("~~~~~~~~~~~~~~~~付款成功~~~~~~~~~");
			outSteam.close();
			inStream.close();
			String result = new String(outSteam.toByteArray(), "utf-8");// 获取微信调用我们notify_url的返回信息
			Map<Object, Object> mapFromXml = WeixinUtils.doXMLParse(result);
			SortedMap<String ,String > sortedMap = new TreeMap();
			if (mapFromXml.get("result_code").toString().equalsIgnoreCase("SUCCESS")) {
				PayLog payLog = this.payLogService.selectPayLogByNo(mapFromXml.get("out_trade_no").toString());
				if(payLog.getStatus()==0){

					String memberId = mapFromXml.get("out_trade_no").toString().split("-")[0];
					Date date = new Date();
					Member member = this.memberService.selectMemberById(memberId);
					if (member==null){
						sortedMap.put("return_code","FAIL");
						sortedMap.put("return_msg","签名失败");
						res.reset();
						res.getWriter().write(parseXML(sortedMap));
					}

					//更新支付记录
					PayLog updatePayLog = new PayLog();
					updatePayLog.setId(payLog.getId());
					updatePayLog.setStatus(1);
					this.payLogService.updatePayLog(updatePayLog);

                    //验签成功后
                    //会员信息 成为会员
                    Member update = new Member();
                    update.setId(memberId);
                    update.setIsVip(MemberIsVip.YES.getValue());
                    this.memberService.updateMember(update);
                    //查询推荐人是否存在 推荐人返利
                    if(member.getIntroUser()!=null){
						this.haoqiCoinRecordService.returnPrice(member.getIntroUser(),payLog.getPrice(),memberId,0);
//                        Member intro = this.memberService.selectMemberById(member.getIntroUser());
//                        //查询推荐人是否存在 状态是否正常 并且推荐人必须也是联盟商
//                        if(intro!=null && intro.getStatus() == MemberStatus.NORMAL.getValue()&&intro.getIsVip().equals(MemberIsVip.YES.getValue())){
//                            //获取下单返费比例
//                            BigDecimal vipReturnRatio = this.shopConfigService.findAll().get(0).getVipReturnRatio();
//                            //计算返费
//                            BigDecimal returnPrice = payLog.getPrice().multiply(vipReturnRatio).multiply(new BigDecimal(0.01)).setScale(2, BigDecimal.ROUND_HALF_DOWN);
//                            //推荐成功进行反馈
//                            HaoqiCoinRecord coinRecord = new HaoqiCoinRecord();
//                            coinRecord.setStatus(1);
//                            coinRecord.setCreated(DateUtils.getNowDate());
//                            coinRecord.setResId(memberId);
//                            coinRecord.setType(0);
//                            coinRecord.setMemberId(member.getIntroUser());
//                            coinRecord.setNum(returnPrice);
//                            coinRecord.setGetType(0);
//                            this.haoqiCoinRecordService.insertHaoqiCoinRecord(coinRecord);
//                            //推荐人的佣金增加
//                            Member introUser = new Member();
//                            introUser.setId(member.getIntroUser());
//                            introUser.setHaoqiCoin(intro.getHaoqiCoin().add(returnPrice));
//                            this.memberService.updateMember(introUser);
//                        }
                    }

				}
				sortedMap.put("return_code","SUCCESS");
				sortedMap.put("return_msg","OK");
				BufferedOutputStream out = new BufferedOutputStream(
						res.getOutputStream());
				out.write(parseXML(sortedMap).getBytes());
				out.flush();
				out.close();

			}else {
				sortedMap.put("return_code","FAIL");
				sortedMap.put("return_msg","签名失败");
				BufferedOutputStream out = new BufferedOutputStream(
						res.getOutputStream());
				out.write(parseXML(sortedMap).getBytes());
				out.flush();
				out.close();
			}
			return "success";
		} catch (Exception e) {
			return "failure";
		}
	}


	//输出XML
	public String parseXML(Map map) {
		StringBuffer sb = new StringBuffer();
		sb.append("<xml>\n");
		Set es = map.entrySet();
		Iterator it = es.iterator();
		while(it.hasNext()) {
			Map.Entry entry = (Map.Entry)it.next();
			String k = (String)entry.getKey();
			String v = (String)entry.getValue();
			if(null != v && !"".equals(v) && !"appkey".equals(k)) {

				sb.append("<" + k +"><![CDATA[" + v + "]]></" + k + ">\n");
			}
		}
		sb.append("</xml>");
		return sb.toString();
	}


}
